package com.jiangyg.mall.db.hibernate.dao;

import com.jiangyg.mall.db.hibernate.mapper.SQLMapper;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate5.SessionFactoryUtils;
import org.springframework.util.Assert;

import javax.validation.constraints.NotNull;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 类描述：通用的数据操作Dao实现
 * 
 * @author jiangyg
 * @date 2020-10-18
 * @version 2.0
 */
public abstract class GenericDaoImpl implements GenericDao {
	
	@NotNull
    @Autowired
    @Qualifier("sqlMapper")
    private SQLMapper mapper;

    @NotNull
    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;

    @Override
    public Session session() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public SessionFactory sessionFactory() {
        Assert.notNull(sessionFactory, "操作数据库失败：sessionFactory为空！");
        return this.sessionFactory;
    }

    @Override
    public Connection connection() throws SQLException {
        return SessionFactoryUtils.getDataSource(sessionFactory).getConnection();
    }

    @Override
    public SQLMapper mapper() {
        Assert.notNull(mapper, "获取mapper失败：mapper为空！");
        return this.mapper;
    }
    
}
